package cn.ml.mybatisdemo.entity;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 映射器映射为(n,n)
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
public class PointTypeHandler extends BaseTypeHandler<Person.Point> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Person.Point point, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i,point.toString());
    }

    @Override
    public Person.Point getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String str = resultSet.getString(s);
        return createPoint(str);
    }

    private Person.Point createPoint(String str) {
        Person.Point point = new Person.Point();
        if(str !=null){
            String num1 = str.substring(1,str.indexOf(","));
            point.setX(Integer.parseInt(num1));
            String num2 = str.substring(str.indexOf(",")+1,str.length()-1);
            point.setY(Integer.parseInt(num2));
        }
        return point;
    }

    @Override
    public Person.Point getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return createPoint(resultSet.getString(i));
    }

    @Override
    public Person.Point getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }
}
